package rwt.server.mtl;

import java.util.*;

import org.slf4j.*;

import rwt.server.core.BaseMessage;
import rwt.server.mtl.ada.AdaMessageAdaptor;
import rwt.server.mtl.java.JavaMessageAdaptor;


public class MessageAdaptorFactory
{
	private static final Logger logger = LoggerFactory.getLogger(MessageAdaptorFactory.class);
	
	/**
	 * Creates a message adaptor that uses the pure-Java port of the Message Translation Library.
	 * 
	 * @param idToClassMap A map of op-codes to corresponding message classes.
	 * @return pure Java message adaptor
	 * @see rwt.server.mtl.java.MessageTranslationLibrary MessageTranslationLibrary
	 */
	public static IMessageAdaptor createPureJavaAdaptor(Map<Integer, Class<? extends BaseMessage>> idToClassMap)
	{
		logger.info("Using the pure-Java message translator");
		setup(idToClassMap);
		return new JavaMessageAdaptor(idToClassMap);
	}
	
	/**
	 * Creates a message adaptor that uses AJIS to interface with the original Message Translation Library
	 * (Ada) in native dll form.
	 * 
	 * @param idToClassMap A map of op-codes to corresponding message classes.
	 * @return native Ada message adaptor
	 */
	public static IMessageAdaptor createAdaNativeAdaptor(Map<Integer, Class<? extends BaseMessage>> idToClassMap)
	{
		logger.info("Using the Ada-native message translator");
		setup(idToClassMap);
		return new AdaMessageAdaptor(idToClassMap);
	}
	
	private static void setup(Map<Integer, Class<? extends BaseMessage>> idToClassMap)
	{
		Map<Class<? extends BaseMessage>, Integer> classToIdMap = new HashMap<>(idToClassMap.size());
		for (Map.Entry<Integer, Class<? extends BaseMessage>> entry : idToClassMap.entrySet())
			classToIdMap.put(entry.getValue(), entry.getKey());
		BaseMessage.setClassToIdMap(classToIdMap);
	}
}
